#!/usr/bin/env bash

set -eu

# Rewrite our arguments to be `cargo build` instead of `cargo wasm`;
# this assumes that the command will always be `cargo wasm ...`. We
# capture the output directory in order to place the result file.
shift # Ignore "wasm"
args=()
while (( "$#" )); do
    if [[ "$1" == "--" ]] ; then
        : # Ignore
    elif [[ "$1" == "-o" ]] ; then
        shift
        output="$1"
    else
        args+="$1"
    fi

    shift
done

# Perform our build
# https://stackoverflow.com/a/7577209/155423
cargo "build" "--target=wasm32-unknown-unknown" ${args[@]+"${args[@]}"}

for wasm in $(find target/ -name '*wasm' -not -path '*/deps/*'); do
    # Garbage collect to make it tidier
    wasm-gc "${wasm}" "${wasm}.gc"

    # Convert to textual format
    wasm2wat \
        --fold-exprs \
        --generate-names \
        --inline-exports \
        --ignore-custom-section-errors \
        -o "${output}.wat" \
        "${wasm}.gc" \
        2> >(grep -v 'invalid linking metadata version: 3' 1>&2)

    # wasm2wat spits out an error that we don't care about, so hide it
    # https://github.com/WebAssembly/wabt/issues/842
    # https://stackoverflow.com/a/15936384/155423
done
